package com.beiye.drivertransport.specifiedLearning.business;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.SpecifiedLearningCourseDetailsAgainActivity;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.adapter.CourseSuperAdatper;
import com.beiye.drivertransport.bean.CourseSuperBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;
//企业管理员课程超市
public class CourseLearnBusinessActivity extends TwoBaseAty {
    private int firstIndex = 1;
    private int pageSize = 10;

    View empty_view;

    LRecyclerView lv_course;

    EditText ed_course;

    TextView tv_search;//搜索

    ImageView img_delet;//清除内容

    ImageView img_businesssafeback;
    private LRecyclerViewAdapter lRecyclerViewAdapter1;
    private CourseSuperAdatper courseSuperAdatper;

    @Override
    public int getLayoutId() {
        return R.layout.activity_course_learn_business;
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_businesssafeback) {
            finish();
        } else if (id == R.id.tv_course) {
            lv_course.refresh();
            LoginUserBean userInfo = UserManger.getUserInfo();
            LoginUserBean.DataBean data = userInfo.getData();
            if (data == null) {
                return;
            }
            String userId = data.getUserId();
            //存储一份readInterval文件
            SharedPreferences sp = getSharedPreferences("CourseLearnBusinessActivity",
                    Context.MODE_PRIVATE);
            int readInterval = sp.getInt("readInterval", 0);
            String orgId = sp.getString("orgId", "");
            if (orgId.equals("")) {
                lv_course.setEmptyView(empty_view);
                lv_course.refreshComplete(0);
                return;
            }
            String coursename = ed_course.getText().toString().trim();
            if (coursename.equals("")) {
                new Login().getPreJobTrainingandcoursesupermaket(userId, orgId, "", 2, readInterval, firstIndex, pageSize, this, 1);
            } else {
                new Login().getPreJobTrainingandcoursesupermaket(userId, orgId, coursename, 2, readInterval, firstIndex, pageSize, this, 1);
            }
        } else if (id == R.id.img_delet) {
            ed_course.setText("");
            img_delet.setVisibility(View.GONE);
        }
    }
    @Override
    public void initData() {
        empty_view = (View) findViewById(R.id.empty_view);
        lv_course = (LRecyclerView) findViewById(R.id.lv_coursesuperbusinessmarket);
        ed_course = (EditText) findViewById(R.id.ed_course);
        tv_search = (TextView)findViewById(R.id.tv_course);
        img_delet = (ImageView)findViewById(R.id.img_delet);
        img_businesssafeback = (ImageView) findViewById(R.id.img_businesssafeback);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        //选中公司方法
        initUi();
        ed_course.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //如果长度为0
                if (charSequence.length() == 0) {
                    img_delet.setVisibility(View.GONE);
                } else {
                    img_delet.setVisibility(View.VISIBLE);

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        ed_course.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    ed_course.setCursorVisible(true);// 再次点击显示光标
                }
                return false;
            }
        });
    }

    @Override
    public void requestData() {
        Bundle bundle = getIntent().getExtras();
        int  readInterval = bundle.getInt("readInterval");
        int  mark = bundle.getInt("Mark");
        String orgId= bundle.getString("orgId");
        SharedPreferences sp = getSharedPreferences("CourseLearnBusinessActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("orgId", orgId);
        editor.putInt("readInterval", readInterval);
        editor.putInt("Mark", mark);
        editor.commit();

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        if (orgId.equals("")) {
            lv_course.setEmptyView(empty_view);
            lv_course.refreshComplete(0);
            return;
        }
        String coursename = ed_course.getText().toString().trim();
        if (coursename.equals("")) {
            new Login().getPreJobTrainingandcoursesupermaket(userId, orgId, "", 2, readInterval, firstIndex, pageSize, this, 1);
        } else {
            new Login().getPreJobTrainingandcoursesupermaket(userId, orgId, coursename, 2, readInterval, firstIndex, pageSize, this, 1);
        }

    }
    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            CourseSuperBean courseSuperBean = JSON.parseObject(result, CourseSuperBean.class);
            if (courseSuperBean != null) {
                try {
                    if (courseSuperBean.getRows() != null && courseSuperBean.getRows().size() > 0) {
                        lv_course.setVisibility(View.VISIBLE);
                        if (firstIndex == 1) {
                            courseSuperAdatper.clear();
                            courseSuperAdatper.setDataList(courseSuperBean.getRows());
                        } else {
                            courseSuperAdatper.addAll(courseSuperBean.getRows());
                        }

                        if (courseSuperBean.getRows().size() < pageSize) {
                            lv_course.setNoMore(true);
                        }
                    } else {
                        if (firstIndex == 1) {//第一页
                            lv_course.setEmptyView(empty_view);
                            courseSuperAdatper.clear();
                        } else {
                            lv_course.setNoMore(true);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                lv_course.refreshComplete(courseSuperBean.getRows() == null ? 0 : courseSuperBean.getRows().size());
                lRecyclerViewAdapter1.notifyDataSetChanged();
            }
        }
//        else if (what == 2) {
//            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//            int code = checkBean.getCode();
//            String msg = checkBean.getMsg();
//            if (code == 0) {
//
//                initcoursesupermaketCheckData();
//            }
//        } else if (what == 3) {
//
//            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//            int code = checkBean.getCode();
//            String msg = checkBean.getMsg();
//            if (code == 0) {
//
//                initcoursesupermaketCheckDateData();//判断是否未完成学习计划
//            }
//        } else if (what == 4) {
//            SpecifiedLearningBusinessBean specifiedLearningBusinessBean = JSON.parseObject(result, SpecifiedLearningBusinessBean.class);
//            List<SpecifiedLearningBusinessBean.RowsBean> rows = specifiedLearningBusinessBean.getRows();
//
//            if (rows.size() == 0) {
//                if (!CameraCanUseUtils.isCameraCanUse()) {
//                    ToastUtil.showShortToast(getActivity(), "请到手机设置界面里找驾运宝允许开启照相");
//                    return;
//                }
//                TiShiDialog.Builder builder = new TiShiDialog.Builder(getContext());
//                builder.setMessage("您已完成本月学习任务，继续浏览课程将不记录学时");
//                builder.setTitle("提示:");
//                builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        //设置你的操作事项
//                        //存储一份readInterval文件
//                        showLoadingDialog("正在加载");
//                        //存储一份readInterval文件
//                        SharedPreferences spp = getActivity().getSharedPreferences("courseSupermarktcSn",
//                                Context.MODE_PRIVATE);
//                        int tcSn = spp.getInt("tcSn", 0);
//                        Bundle bundle = new Bundle();
//                        bundle.putInt("tcsn", tcSn);
//                        SharedPreferences sp = getActivity().getSharedPreferences("CourseLearnBusinessActivity",
//                                Context.MODE_PRIVATE);
//                        int readInterval = sp.getInt("readInterval", 0);
//                        bundle.putInt("readInterval", readInterval);
//                        String orgId = sp.getString("orgId", "");
//                        int minPer = sp.getInt("minPer", 0);
//                        bundle.putString("orgId", orgId);
//                        bundle.putInt("minPer", minPer);
//                        bundle.putInt("atpSn", -1);
//                        startActivity(CourseSupermarketBusinessDetailsActivity.class, bundle);
//                    }
//                });
//
//                builder.setNegativeButton("取消",
//                        new android.content.DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//
//                builder.create().show();
//
//            } else {
//
//                planList.clear();
//                for (int i = 0; i < rows.size(); i++) {
//                    if (rows.get(i).getFinishMark() == 0) {
//                        planList.add(rows.get(i));
//                    }
//                }
//
//                mPopWindowPlanApt = new PopWindowPlanApt(getContext(), planList, R.layout.popwindow_dateitem_layout);
//                showPopupWindowDate(planList);//弹出未完成时
//            }
//
//        }
        super.onSuccess(result, call, response, what);

    }

    @Override
    protected void onResume() {
        lv_course.refresh();
        requestData();
        super.onResume();
    }
    private void initUi() {
        LinearLayoutManager ms = new LinearLayoutManager(CourseLearnBusinessActivity.this);
        ms.setOrientation(LinearLayoutManager.VERTICAL);
        lv_course.setLayoutManager(ms);
        courseSuperAdatper = new CourseSuperAdatper(CourseLearnBusinessActivity.this);
        lRecyclerViewAdapter1 = new LRecyclerViewAdapter(courseSuperAdatper);
        lv_course.setAdapter(lRecyclerViewAdapter1);
        lv_course.setFooterViewColor(R.color.colorAccent, R.color.dark, android.R.color.white);
        lv_course.setFooterViewHint("拼命加载中", "已经全部为你呈现了", "网络不给力啊，点击再试一次吧");
        lv_course.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                firstIndex = 1;
                requestData();
            }
        });

        lv_course.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {
                firstIndex += pageSize;
                requestData();
            }
        });
        empty_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lv_course.refresh();
            }
        });

        lRecyclerViewAdapter1.setOnItemClickListener(new com.github.jdsjlzx.interfaces.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (Utils.isFastClicker()) {
                    return;
                }
                showLoadingDialog("");
                int tcSn = courseSuperAdatper.getDataList().get(position).getTcSn();
                Bundle bundle = new Bundle();
                bundle.putInt("tcsn", tcSn);
                startActivity(SpecifiedLearningCourseDetailsAgainActivity.class, bundle);

//                try {
//                    SharedPreferences sp1 = getActivity().getSharedPreferences("CourseLearnBusinessActivity", Context.MODE_PRIVATE);
//                    int mark = sp1.getInt("Mark", 1);
//                    if (mark == 0) {
//                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getActivity());
//                        builder1.setMessage("您已被企业管理员禁用,请联系企业管理员");
//                        builder1.setTitle("提示:");
//                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                                //设置你的操作事项
//                            }
//                        });
//                        builder1.create().show();
//                        return;
//                    }
//                    //校验是否学过课程
//                    int tcSn = courseSuperAdatper.getDataList().get(position).getTcSn();
//                    //存储一份tcSn文件
//                    SharedPreferences sp = getActivity().getSharedPreferences("courseSupermarktcSn",
//                            Context.MODE_PRIVATE);
//                    SharedPreferences.Editor editor = sp.edit();
//                    editor.putInt("tcSn", tcSn);
//                    editor.commit();
//                    initspeciacoursesupermaketCheckData();
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        });
        lv_course.refresh();

    }
   
}
